<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

// 检查用户登录状态
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => '未登录']);
    exit;
}

try {
    // 获取当前轮次信息
    $current_round = getCurrentRound();
    $round_id = isset($_GET['round_id']) ? intval($_GET['round_id']) : $current_round['id'];
    
    // 获取指定轮次的所有交易记录
    $stmt = $pdo->prepare("
        SELECT 
            t.id,
            t.user_id,
            u.username,
            t.type,
            t.quantity,
            t.price,
            t.amount,
            t.profit,
            t.fee,
            t.transaction_time
        FROM 
            transactions t
        JOIN 
            users u ON t.user_id = u.id
        WHERE 
            t.round_id = ?
        ORDER BY 
            t.transaction_time DESC
    ");
    
    $stmt->execute([$round_id]);
    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // 获取轮次信息
    $stmt = $pdo->prepare("SELECT round_number, status FROM game_rounds WHERE id = ?");
    $stmt->execute([$round_id]);
    $round_info = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // 处理交易记录，保护用户隐私（只显示用户名的前两个字符和后两个字符）
    foreach ($transactions as &$transaction) {
        $username = $transaction['username'];
        $length = mb_strlen($username, 'UTF-8');
        
        if ($length > 4) {
            $transaction['username'] = mb_substr($username, 0, 1, 'UTF-8') . '***' . mb_substr($username, -1, 1, 'UTF-8');
        } else if ($length > 2) {
            $transaction['username'] = mb_substr($username, 0, 1, 'UTF-8') . '**';
        } else {
            $transaction['username'] = $username[0] . '*';
        }
        
        // 转换时间格式
        $transaction['transaction_time'] = date('H:i:s', strtotime($transaction['transaction_time']));
        
        // 格式化数值
        $transaction['quantity'] = floatval($transaction['quantity']);
        $transaction['price'] = floatval($transaction['price']);
        $transaction['amount'] = floatval($transaction['amount']);
        $transaction['profit'] = floatval($transaction['profit']);
        $transaction['fee'] = floatval($transaction['fee']);
        
        // 移除敏感信息
        unset($transaction['user_id']);
    }
    
    echo json_encode([
        'success' => true,
        'transactions' => $transactions,
        'round_info' => $round_info
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => '获取交易记录失败: ' . $e->getMessage()
    ]);
}
?>
